package 迭代遍历;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author: zhengtao
 * @description: 二叉树的中序遍历 ,迭代遍历。非递归遍历
 * @version: 1.0
 * @date: 2022/10/29  09:48
 */
public class Demo94 {
    List<Integer> res=new ArrayList<>();
    public List<Integer> inorderTraversal(TreeNode root) {
        Stack<TreeNode> stack=new Stack<>();
        //定义指针去遍历节点，指针为空，则出栈,并且赋值cur为出栈元素的右节点，
        TreeNode cur=root;
        while (!stack.empty()||cur!=null){
              if (cur!=null){
                  stack.push(cur);
                  cur=cur.left;
              }else {
                  TreeNode pop = stack.pop();
                  res.add(pop.val);
                  //指向出栈元素的右节点
                  cur=pop.right;
              }
        }
        return res;
    }

    /**
     * Definition for a binary tree node.
     * */
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
